package com.lagou.edu.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * @param
 * @author oyz
 * @version 1.0.4
 * @description: gateway的全局过滤器
 * @date 2022/5/9 8:36
 */
@Component
@Slf4j
public class BlackListFilter implements GlobalFilter, Ordered {

    /**
     * 自定义黑名单
     */
    private static List<String> blackList = new ArrayList<>();


    static{
        blackList.add("0:0:0:0:0:0:0:1");
    }

    /**
     * 过滤器核心方法
     * @param exchange 封装了request和response请求
     * @param chain 过滤器的调用链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求
        ServerHttpRequest request = exchange.getRequest();
        // 获取响应
        ServerHttpResponse response = exchange.getResponse();
        // 拿到ip地址
        String hostString = request.getRemoteAddress().getHostString();
        // 判断是否在黑名单里边存在
        if(blackList.contains(hostString)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String text = "request is refused";
            DataBuffer wrap = response.bufferFactory().wrap(text.getBytes());
            log.debug("拦截请求ip=====>:"+request);
            return response.writeWith(Mono.just(wrap));
        }
        // 合法请求，放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
